/**
 * 
 */
package cn.com.xf.service.impl;

import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.SimpleHttpConnectionManager;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.params.HttpClientParams;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.DateFormatUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import cn.com.xf.common.Constants;
import cn.com.xf.dao.SmsToAppDAO;
import cn.com.xf.dao.TbAppDeviceDAO;
import cn.com.xf.dao.TblOaNoticeDAO;
import cn.com.xf.dao.TblOaNoticeReadDAO;
import cn.com.xf.dao.VDstareaDAO;
import cn.com.xf.domain.SmsToApp;
import cn.com.xf.domain.TblOaNotice;
import cn.com.xf.domain.TblOaNoticeRead;
import cn.com.xf.domain.VDstarea;
import cn.com.xf.service.NoticeService;
import cn.com.xf.utils.ATest;
import cn.com.xf.web.security.UserInfo;

/**
 * @author Administrator
 * 
 */
@Service
public class NoticeServiceImpl implements NoticeService {
	
	Log log = LogFactory.getLog(NoticeServiceImpl.class);
	
	@Autowired
	private TblOaNoticeDAO coreNoticeDAO;
	@Autowired
	private TblOaNoticeReadDAO tblOaNoticeReadDAO;
	@Autowired
	private VDstareaDAO vDstareaDAO;
	@Autowired
	private SmsToAppDAO toAppDAO;
	@Autowired
	private TbAppDeviceDAO appDeviceDAO;
	@Autowired
	private ThreadPoolTaskExecutor taskExecutor;

	
	static String  notice_key = "{40E809C5-74AF-4ABD-914B-02F99032FC1C}";
	static String url = "http://218.16.125.163:20002/xfplatform-message-0.0.1-SNAPSHOT/App/a6ToAppNotice";
		
	@Override
	public List<TblOaNotice> selectNotice(int begin, int pageSize, String orderByField, String orderByMode,
			String title, String viceTitle, String isimportant, String istop, String group, String center) {
		List<TblOaNotice> list = coreNoticeDAO.selectAndOrder(begin, pageSize, orderByField, orderByMode, title,
				viceTitle, isimportant, istop, group, center);
		return list;
	}

	@Override
	public int selectNoticeCount(String title, String viceTitle, String isimportant, String istop, String group, String center) {
		return coreNoticeDAO.selectNoticeCount(title, viceTitle, isimportant, istop, group, center);
	}

	@Override
	public int insertNotice(TblOaNotice coreNotice) {
		String docNumber = "";
		if (Constants.NOTICE_GROUP_NOTICE.equalsIgnoreCase(coreNotice.getNoticeGroup())) {
			// 1.获取文件编号			
			String currentDocNumber = coreNoticeDAO.selectCurrentDocNumber();
			// 发布日期
			String dateStr = coreNotice.getPublicTimeStr();
			String year = dateStr.substring(0, 4);
			String month = dateStr.substring(5, 7);
			if (null == currentDocNumber) {
				// 如果空值创建文件编号
				docNumber = year + month + "001";
			} else if (StringUtils.isBlank(currentDocNumber)) {
				docNumber = year + month + "001";
			} else {
				// 读取已经存在的最大文件编号
				String nYear = "";
				String nMonth = "";
				String nCode = "";
				String oYear = currentDocNumber.substring(0, 4);
				String oMonth = currentDocNumber.substring(4, 6);
				if (oYear.equalsIgnoreCase(year)) {
					if (oMonth.equalsIgnoreCase(month)) {
						String oMax = currentDocNumber.substring(6, 9);
						nCode = (Integer.valueOf(oMax) + 1) + "";
						if (nCode.length() == 1) {
							nCode = "00" + nCode;
						} else if (nCode.length() == 2) {
							nCode = "0" + nCode;
						} else if (nCode.length() == 4) {
							nCode = "999";
						}
						nYear = oYear;
						nMonth = oMonth;
					} else {
						nYear = oYear;
						nMonth = month;
						nCode = "001";
					}
				} else {
					nYear = year;
					nMonth = month;
					nCode = "001";
				}
				docNumber = nYear + nMonth + nCode;
			}
			coreNotice.setDocNumber(docNumber);
		} else if (Constants.NOTICE_GROUP_DAILY.equalsIgnoreCase(coreNotice.getNoticeGroup())) {
			coreNotice.setSendto(null);
			coreNotice.setCopyto(null);
			coreNotice.setPublicDepart(null);
			coreNotice.setDocNumber(null);
		}
		String name = SecurityContextHolder.getContext().getAuthentication().getName();
		Date addDate = new Date();
		coreNotice.setAddTime(addDate);
		coreNotice.setAddUser(name);
		coreNoticeDAO.insertSelective(coreNotice);
		Long noticeId = coreNotice.getNoticeId();
		if (Constants.NOTICE_GROUP_NOTICE.equalsIgnoreCase(coreNotice.getNoticeGroup())){
			String toZB = null!=coreNotice.getToZB()?coreNotice.getToZB():"";
			String toZJ = null!=coreNotice.getToZJ()?coreNotice.getToZJ():"";
			String toFJ = null!=coreNotice.getToFJ()?coreNotice.getToFJ():"";
			
			if(!toZB.equals("1")&&!toZJ.equals("1")&&!toFJ.equals("1")){
				return -1;
			}
			
			String centerId = "";
			if(toZB.equals("1")){
				centerId = "769000";
				coreNoticeDAO.insertNoticeMapping(centerId,noticeId);
			}
			if(toZJ.equals("1")){
				centerId = "570000";
				coreNoticeDAO.insertNoticeMapping(centerId,noticeId);
			}
			if(toFJ.equals("1")){
				centerId = "591000";
				coreNoticeDAO.insertNoticeMapping(centerId,noticeId);
			}
		}
		final String group = coreNotice.getNoticeGroup();
		String toApp = null!=coreNotice.getToApp()?coreNotice.getToApp():"";
		if(group.equals("0") && toApp.equals("1")){
			final String msgRefid = coreNoticeDAO.selectNoticeId(docNumber)+"";
			final String msgContent = coreNotice.getTitle();
			final Short msgStatus = 0;
			final String msgType = "0";
			final String msgSendtimeStr = DateFormatUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss");
			final String msgEntertimeStr = DateFormatUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss");
			final String msgBatid = DateFormatUtils.format(new Date(),"yyyyMMddHHmmss")+msgRefid;
			final String msgEnteruser = coreNotice.getPublicManId();
			taskExecutor.execute(new Runnable() {
				@Override
				public void run() {
					List<SmsToApp> toAppList = new ArrayList<SmsToApp>();
					List<String> userList= appDeviceDAO.selectAppUser();
					for (int i = 0; i < userList.size(); i++) {
						String msgUserid = userList.get(i);
						SmsToApp toApp = new SmsToApp();
						toApp.setMsgBatid(msgBatid);
						toApp.setMsgContent(msgContent);
						toApp.setMsgEntertimeStr(msgEntertimeStr);
						toApp.setMsgSendtimeStr(msgSendtimeStr);
						toApp.setMsgRefid(msgRefid);
						toApp.setMsgUserid(msgUserid);
						toApp.setMsgStatus(msgStatus);
						toApp.setMsgType(msgType);
						toApp.setMsgEnteruser(msgEnteruser);
						toAppList.add(toApp);
					}					
					toAppDAO.insertBatch(toAppList);
					String signdata = ATest.getMd5Sign(msgEnteruser+msgRefid+msgBatid+group+notice_key);
					//String para = "aEnterUser="+msgEnteruser+"&aNoticeId="+msgRefid+"&batId="+msgBatid+"&noticeType="+group+"&signdata="+signdata;
					try {
						String result  = sendGet(url, msgEnteruser, msgRefid, msgBatid, group, signdata);
					} catch (Exception e) {
						log.error("NoticeServiceImpl发送a6ToAppNotice接口错误："+e.getMessage());
					}
				}
			});				
		}
		return 0;
	}
	
	public static String sendGet(String url,String msgEnteruser,String msgRefid,String msgBatid,String group,String signdata) throws Exception{
		HttpClient httpClient = new HttpClient(new HttpClientParams(),new SimpleHttpConnectionManager(true));
		GetMethod method = null;
		Map<String, Object> map = new HashMap<String, Object>();
		msgEnteruser = URLEncoder.encode(msgEnteruser,"GBK");
		msgRefid = URLEncoder.encode(msgRefid,"GBK");
		msgBatid = URLEncoder.encode(msgBatid,"GBK");
		group=URLEncoder.encode(group,"GBK");
		signdata =URLEncoder.encode(signdata,"GBK");
		String para = "?aEnterUser="+msgEnteruser+"&aNoticeId="+msgRefid+"&batId="+msgBatid+"&noticeType="+group+"&signdata="+signdata;
		try {
		String GetURL = url+para;
			method = new GetMethod(GetURL);			
            //使用系统提供的默认的恢复策略
            method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());
            //设置超时的时间
            method.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 10000);
            int statusCode = httpClient.executeMethod(method);            
        	method.getParams().setContentCharset("UTF-8");
        	String json = method.getResponseBodyAsString();
        	return json.toString();
		} finally {
			if(method != null) { //不要忘记释放，尽量通过该方法实现，
				method.releaseConnection();
			}
		}
	}
	
	
	@Override
	public TblOaNotice selectNoticeById(Integer id) {
		TblOaNotice coreNotice = coreNoticeDAO.selectByPrimaryKey((long) id);
		return coreNotice;
	}

	@Override
	public int updateNotice(TblOaNotice coreNotice) {
		Long noticeId = coreNotice.getNoticeId();
		TblOaNotice old = coreNoticeDAO.selectByPrimaryKey(noticeId);
		old.setTitle(coreNotice.getTitle());
		old.setViceTitle(coreNotice.getViceTitle());
		old.setContent(coreNotice.getContent());
		old.setIsimportant(coreNotice.getIsimportant());
		old.setIstop(coreNotice.getIstop());
		old.setPublicMan(coreNotice.getPublicMan());
		if (Constants.NOTICE_GROUP_NOTICE.equalsIgnoreCase(old.getNoticeGroup())) {
			old.setPublicDepart(coreNotice.getPublicDepart());
			old.setSendto(coreNotice.getSendto());
			old.setCopyto(coreNotice.getCopyto());
		}
		String loginName = SecurityContextHolder.getContext().getAuthentication().getName();
		old.setUpdateTime(new Date());
		old.setUpdateUser(loginName);
		coreNoticeDAO.updateByPrimaryKeySelective(old);
		
		//判断是否是总部账号
		UserInfo user = (UserInfo)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		String siteId = user.getSiteId();
		if(siteId.equals("10000")||"769000".equals(selectOfCenter(user.getSiteId()))){
			List<String> regions = selectRegions(Integer.parseInt(noticeId.toString()));
			//判断公告是浙江的还是总部的
			String hasZJNotice = "";
			String hasZBNotice = "";
			String hasFJNotice = "";
			for(String id:regions){
				if("570000".equals(id)){
					hasZJNotice = "1";
				}else if("769000".equals(id)){
					hasZBNotice = "1";
				}else if("591000".equals(id)){
					hasFJNotice = "1";
				}
			}
			
			String toZB = null!=coreNotice.getToZB()?coreNotice.getToZB():"";
			String toZJ = null!=coreNotice.getToZJ()?coreNotice.getToZJ():"";
			String toFJ = null!=coreNotice.getToFJ()?coreNotice.getToFJ():"";
			if(!toZB.equals("1")&&!toZJ.equals("1")&&!toFJ.equals("1")){
				return -1;
			}
			String centerId = "";
			//检查总部可见性
			if(toZB.equals("1")){
				if(!hasZBNotice.equals("1")){
					centerId = "769000";
					coreNoticeDAO.insertNoticeMapping(centerId,noticeId);
				}
			}else{
				if(hasZBNotice.equals("1")){
					centerId = "769000";
					coreNoticeDAO.deleteNoticeMappingByCenterId(new Long(noticeId), centerId);
				}
			}
			//检查浙江可见性
			if(toZJ.equals("1")){
				if(!hasZJNotice.equals("1")){
					centerId = "570000";
					coreNoticeDAO.insertNoticeMapping(centerId,noticeId);
				}
			}else{
				if(hasZJNotice.equals("1")){
					centerId = "570000";
					coreNoticeDAO.deleteNoticeMappingByCenterId(new Long(noticeId), centerId);
				}
			}
			//检查福建可见性
			if(toFJ.equals("1")){
				if(!hasFJNotice.equals("1")){
					centerId = "591000";
					coreNoticeDAO.insertNoticeMapping(centerId,noticeId);
				}
			}else{
				if(hasFJNotice.equals("1")){
					centerId = "591000";
					coreNoticeDAO.deleteNoticeMappingByCenterId(new Long(noticeId), centerId);
				}
			}
		}
		return 0;
	}

	@Override
	public int deleteByNoticeId(String noticeId) {
		coreNoticeDAO.deleteByPrimaryKey(new Long(noticeId));
		return coreNoticeDAO.deleteNoticeMappingByPrimaryKey(new Long(noticeId));
	}

	@Override
	public List<TblOaNotice> selectPrevAndNextById(String noticeId, String group, String centerId) {
		return coreNoticeDAO.selectPrevAndNext(noticeId, group,centerId);
	}

	@Override
	public int insertNoticeRead(String noticeId, String empId, String group) {
		// 1.检查存在性
		TblOaNoticeRead read = tblOaNoticeReadDAO.selectByNoticeIdAndRecordId(noticeId, empId);
		if (null == read) {
			// 2.插入一条读过的记录
			TblOaNoticeRead record = new TblOaNoticeRead();
			record.setNid(noticeId);
			record.setEmpid(empId);
			record.setReadtime(new Date());
			record.setTypeid(0);
			tblOaNoticeReadDAO.insert(record);
		}
		return 0;
	}

	@Override
	public List<VDstarea> selectMobiles() {
		return vDstareaDAO.selectMobiles();
	}

	@Override
	public String selectOfCenter(String siteId) {
		return coreNoticeDAO.selectOfCenter(siteId);
	}

	@Override
	public List<String> selectRegions(Integer id) {
		List<String> list = coreNoticeDAO.selectRegionsById((long) id);
		return list;
	}
	
	
}
